﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Globalization;

namespace NAntMenu.Core
{
    internal class NAntBuildRunnerArguments
    {
        public string NAntExeFilePath { get; set; }
        public string BuildFilePath { get; set; }
        public string TargetName {get; set;}
        public bool ShowPrompt { get; set; }

        public NAntBuildRunnerArguments(
            string nantExeFilePath, 
            string buildFilePath, 
            string targetName)
        {
            this.NAntExeFilePath = nantExeFilePath;
            this.BuildFilePath = buildFilePath;
            this.TargetName = targetName;
        }
    }

    public class NAntBuildRunner
    {
        private string NAntExeFilePath { get; set; }
        private string BuildFilePath { get; set; }
        private BackgroundWorker nantbuildRunner;

        private bool runAsAdministrator;

        public NAntBuildRunner(string nantExeFilePath, string buildFilePath)
        {
            this.NAntExeFilePath = nantExeFilePath;
            this.BuildFilePath = buildFilePath;
        }

        public void Run(string targetName)
        {
            this.nantbuildRunner = new System.ComponentModel.BackgroundWorker();
            this.nantbuildRunner.WorkerReportsProgress = true;
            this.nantbuildRunner.WorkerSupportsCancellation = true;
            this.nantbuildRunner.DoWork += new System.ComponentModel.DoWorkEventHandler(this.BackgroundWorkerDoWork);
            this.nantbuildRunner.RunWorkerAsync(
                new NAntBuildRunnerArguments(
                    this.NAntExeFilePath,
                    this.BuildFilePath,
                    targetName));
        }

        public void RunAsAdministrator(string targetName)
        {
            runAsAdministrator = true;
            Run(targetName);
        }

        private void BackgroundWorkerDoWork(object sender, DoWorkEventArgs e)
        {
            NAntBuildRunnerArguments args = (NAntBuildRunnerArguments)e.Argument;
            Process p = new Process
            {
                StartInfo =
                {
                    FileName = args.NAntExeFilePath,
                    Verb = runAsAdministrator ? "runas" : null,
                    WorkingDirectory = Path.GetDirectoryName(args.BuildFilePath),
                    Arguments =
                        String.Format(
                            CultureInfo.InvariantCulture,
                            "-buildfile:\"{0}\" \"{1}\" -logger:NAntMenu.Logger.BuildOutputLogger",
                            args.BuildFilePath,
                            args.TargetName)
                }
            };
            p.Start();
            p.WaitForExit();
        }
    }
}
